package com.ruoyi.djb.task;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.djb.controller.BaseController;
import com.ruoyi.djb.domain.*;
import com.ruoyi.djb.mapper.*;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.ruoyi.common.utils.DateUtils.YYYY_MM_DD_HH_MM_SS;
import static com.ruoyi.djb.config.Constants.*;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Component("djbTask")
public class DjbTask extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(DjbTask.class);

    @Resource
    private DjbRegistryMapper registryMapper;
    @Resource
    private DjbUserLimitMapper userLimitMapper;
    @Resource
    private DjbDistrictMapper districtMapper;
    @Resource
    private DjbReleaseMapper releaseMapper;
    @Resource
    private DjbTagMapper tagMapper;
    @Resource
    private DjbTradeMapper tradeMapper;

    /*任务：修改本日全天 修改明日全天 cron 1 0 0 * * ? */
    public void updateRegistryList(){
        log.info("任务开始：修改本日全天 修改明日全天");
        Calendar calendar = Calendar.getInstance();
        Date date = DateUtils.getNowDate();
        calendar.setTime(date);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)-1, 0, 0, 0);
        /*昨天0点*/
        Date yesterdayZero = calendar.getTime();
        Date todayZero=DateUtils.addDays(yesterdayZero,1);

        /*修改昨天的本日全天为已放行*/
        DjbRegistry registry = new DjbRegistry();
        registry.setType(TYPE_TODAY_WHOLE);
        registry.setStatus(SYS_NO);
        List<DjbRegistry> djbRegistries = registryMapper.selectDjbRegistryList(registry);
        for(DjbRegistry tmp : djbRegistries){
//            if(tmp.getCreateTime().after(yesterdayZero)&&tmp.getCreateTime().before(todayZero)){
            if(tmp.getCreateTime().before(todayZero)){
                tmp.setStatus(SYS_STATUS_PASS);
                registryMapper.updateDjbRegistry(tmp);
            }
        }

        /*修改昨天未放行的本日单次为已作废*/
        DjbRegistry registry4 = new DjbRegistry();
        registry4.setType(TYPE_TODAY_ONE);
        registry4.setStatus(SYS_NO);
        List<DjbRegistry> djbRegistries4 = registryMapper.selectDjbRegistryList(registry4);
        for(DjbRegistry tmp : djbRegistries4){
//            if(tmp.getCreateTime().after(yesterdayZero)&&tmp.getCreateTime().before(todayZero)){
            if(tmp.getCreateTime().before(todayZero)){
                tmp.setStatus(SYS_STATUS_EXPIRE);
                registryMapper.updateDjbRegistry(tmp);
            }
        }

        /*修改昨天未审核的为已作废*/
        DjbRegistry registry6 = new DjbRegistry();
        registry6.setStatus(SYS_EXAM);
        List<DjbRegistry> djbRegistries6 = registryMapper.selectDjbRegistryList(registry6);
        for(DjbRegistry tmp : djbRegistries6){
            if(tmp.getCreateTime().after(yesterdayZero)&&tmp.getCreateTime().before(todayZero)){
                tmp.setStatus(SYS_STATUS_EXPIRE);
                registryMapper.updateDjbRegistry(tmp);
            }
        }

        /*修改昨天登记的明日全天为今日全天*/
        DjbRegistry registry2 = new DjbRegistry();
        registry2.setType(TYPE_TOMORROW_WHOLE);
        registry2.setStatus(SYS_NO);
        List<DjbRegistry> djbRegistries2 = registryMapper.selectDjbRegistryList(registry2);
        for(DjbRegistry tmp : djbRegistries2){
            if(tmp.getCreateTime().after(yesterdayZero)&&tmp.getCreateTime().before(todayZero)){
                tmp.setType(TYPE_TODAY_WHOLE);
                registryMapper.updateDjbRegistry(tmp);
            }
        }

        /*修改昨天登记的明日单次为今日单次*/
        DjbRegistry registry3 = new DjbRegistry();
        registry3.setType(TYPE_TOMORROW_ONE);
        registry3.setStatus(SYS_NO);
        List<DjbRegistry> djbRegistries3 = registryMapper.selectDjbRegistryList(registry3);
        for(DjbRegistry tmp : djbRegistries3){
            if(tmp.getCreateTime().after(yesterdayZero)&&tmp.getCreateTime().before(todayZero)){
                tmp.setType(TYPE_TODAY_ONE);
                registryMapper.updateDjbRegistry(tmp);
            }
        }

        /*修改大前天登记的连续三天为已放行*/
        DjbRegistry registry5 = new DjbRegistry();
        registry5.setType(TYPE_THREE_DAY);
        registry5.setStatus(SYS_NO);
        List<DjbRegistry> djbRegistries5 = registryMapper.selectDjbRegistryList(registry5);

        Date zero3=DateUtils.addDays(yesterdayZero,-2);
        Date zero2=DateUtils.addDays(yesterdayZero,-1);

        for(DjbRegistry tmp : djbRegistries5){
            if(tmp.getCreateTime().after(zero3)&&tmp.getCreateTime().before(zero2)){
                tmp.setStatus(SYS_YES);
                registryMapper.updateDjbRegistry(tmp);
            }
        }

        /*修改前天登记的连续两天为已放行*/
        DjbRegistry registry7 = new DjbRegistry();
        registry7.setType(TYPE_TWO_DAY);
        registry7.setStatus(SYS_NO);
        List<DjbRegistry> djbRegistries7 = registryMapper.selectDjbRegistryList(registry7);

        for(DjbRegistry tmp : djbRegistries7){
            if(tmp.getCreateTime().after(zero2)&&tmp.getCreateTime().before(yesterdayZero)){
                tmp.setStatus(SYS_YES);
                registryMapper.updateDjbRegistry(tmp);
            }
        }

        /*删除30天之前的用户限制*/
        List<DjbUserLimit> djbUserLimits = userLimitMapper.selectDjbUserLimitList(new DjbUserLimit());
        for(DjbUserLimit tmp: djbUserLimits){
            if(tmp.getExpireTime().before(todayZero)){
                userLimitMapper.deleteDjbUserLimitById(tmp.getId());
            }
        }

        log.info("任务结束：");
    }

    /*任务：修改本日全天 修改明日全天 cron 1 0 0 * * ? */
    public void updateNight(){
        DjbRegistry registry = new DjbRegistry();
        registry.setType("夜间场景");
        registry.setStatus(SYS_NO);
        List<DjbRegistry> djbRegistries = registryMapper.selectDjbRegistryList(registry);
        Date date = DateUtils.getNowDate();
        for(DjbRegistry tmp : djbRegistries){
            if(DateUtils.differentBySecond(tmp.getCreateTime(),date)>1800){
                tmp.setStatus(SYS_STATUS_EXPIRE);
                registryMapper.updateDjbRegistry(tmp);
            }
        }
    }

    /*任务：每分钟检查一次 是否超时 */
    public void checkCarRestTimeOut(){
        DjbDistrict district = new DjbDistrict();
        Calendar calendar = Calendar.getInstance();
        Date date = DateUtils.getNowDate();
        calendar.setTime(date);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        /*今天0点*/
        Date todayZero = calendar.getTime();
        List<DjbDistrict> djbDistricts = districtMapper.selectDjbDistrictList(district);
        for(DjbDistrict tmp : djbDistricts){
            if(tmp.getCarRestSwitch()==0)continue;
            DjbRelease query = new DjbRelease();
            query.setDistrictId(tmp.getId());
            query.setType("本日单次");
//            query.setCreateTime(todayZero);
            query.setHasFlag(0);
            query.setUserType(1);
            HashMap<String, Object> map = new HashMap<>();
            map.put("beginTime", DateFormatUtils.format(todayZero,YYYY_MM_DD_HH_MM_SS));
            query.setParams(map);
            List<DjbRelease> djbReleaseList = releaseMapper.selectDjbReleaseList(query);
            for(DjbRelease tmp2 : djbReleaseList){
                if(tmp2.getHasFlag()==1)continue;
                if(DateUtils.differentBySecond(tmp2.getReleaseTime(),date)>tmp.getCarRestTime()*60){
                    /*标记*/
                    if(tmp.getCarRestFlag()==1){
                        DjbTag tag = new DjbTag();
                        tag.setCar(tmp2.getName());
                        tag.setTag("违规超时停放");
                        tag.setDistrictId(tmp.getId());
                        tag.setCreateTime(DateUtils.getNowDate());
                        if(tmp2.getCreateType().equals(CREATE_TYPE_VISITOR)){
                            tag.setUserId(tmp2.getUserId());
                        }
                        tagMapper.insertDjbTag(tag);
                        tmp2.setTag("违规超时停放");
                    }
                    /*发短信*/
                    if(tmp.getCarRestSms()==1&&district.getVipOutTimeSms()==SYS_YES&&district.getBalance()>10){
                        DefaultProfile profile = DefaultProfile.getProfile("cn-qingdao", "LTAIw5DUpj6wdXJ2", "dJQG5ShMic015K9lVdEbhvSOM7wfbr");
                        IAcsClient client = new DefaultAcsClient(profile);
                        CommonRequest request;
                        request = new CommonRequest();
                        request.setSysMethod(MethodType.POST);
                        request.setSysDomain("dysmsapi.aliyuncs.com");
                        request.setSysVersion("2017-05-25");
                        request.setSysAction("SendSms");
                        request.putQueryParameter("PhoneNumbers", tmp2.getMobile());
                        request.putQueryParameter("SignName", "小门官");
                        request.putQueryParameter("TemplateCode", "SMS_480175053");
                        JSONObject jo=new JSONObject();
//                        jo.put("name",tmp2.getName().substring(0,2)+(tmp2.getName().length()==8?"****":"***")+tmp2.getName().substring(tmp2.getName().length()-1));
                        jo.put("code",tmp2.getName());
                        jo.put("address",tmp2.getAddress());
                        request.putQueryParameter("TemplateParam", jo.toString());
                        try {
                            CommonResponse response2 = client.getCommonResponse(request);
                            jo=JSONObject.parseObject(response2.getData());
                            if(jo.getString("Code").equals("OK")){
                            }else{
                                System.out.println("发送短信错误:"+jo.toJSONString());
                            }
                        } catch (ClientException e) {
                            e.printStackTrace();
                            logger.error("发送短信错误:"+e.getMessage());
                        }
                    }
                    tmp2.setHasFlag(1);
                    releaseMapper.updateDjbRelease(tmp2);
                    /*扣费*/
                    district.setBalance(district.getBalance()-10);
                    districtMapper.updateDjbDistrict(district);
                    DjbTrade djbTrade = new DjbTrade();
                    djbTrade.setChargeId(null);
                    djbTrade.setDistrictId(district.getId());
                    djbTrade.setUserId(null);
                    djbTrade.setMoney(10);
                    djbTrade.setCreateTime(DateUtils.getNowDate());
                    djbTrade.setTradeTime(DateUtils.getNowDate());
                    djbTrade.setPayType("");
                    djbTrade.setStatus(SYS_YES);
                    djbTrade.setName("超时短信提醒服务");
                    djbTrade.setDirect("出");
                    djbTrade.setTradeType("消费");
                    djbTrade.setBalance(district.getBalance());
                    tradeMapper.insertDjbTrade(djbTrade);

                }
            }
        }

        DjbRegistry registry = new DjbRegistry();
        registry.setType("夜间场景");
        registry.setStatus(SYS_NO);
        List<DjbRegistry> djbRegistries = registryMapper.selectDjbRegistryList(registry);
        for(DjbRegistry tmp : djbRegistries){
            if(DateUtils.differentBySecond(tmp.getCreateTime(),date)>1800){
                tmp.setStatus(SYS_STATUS_EXPIRE);
                registryMapper.updateDjbRegistry(tmp);
            }
        }
    }

    /*任务：每天0点5分扣费一次-- 免广告 */
    public void vipNoAd(){
        DjbDistrict district = new DjbDistrict();
        Date nowDate = DateUtils.getNowDate();
        Calendar calendar = Calendar.getInstance();
        Date date = DateUtils.getNowDate();
        calendar.setTime(date);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        /*今天0点*/
        Date todayZero = calendar.getTime();
        district.setVipNoAd(SYS_YES);
        List<DjbDistrict> djbDistricts = districtMapper.selectDjbDistrictList(district);
        for(DjbDistrict tmp : djbDistricts){
            if(tmp.getBalance()>100){
                /**/
                district.setBalance(district.getBalance()-100);
                DjbTrade djbTrade = new DjbTrade();
                djbTrade.setChargeId(null);
                djbTrade.setDistrictId(tmp.getId());
                djbTrade.setUserId(null);
                djbTrade.setMoney(100);
                djbTrade.setCreateTime(nowDate);
                djbTrade.setTradeTime(nowDate);
                djbTrade.setPayType("");
                djbTrade.setStatus(SYS_YES);
                djbTrade.setName("免登记广告");
                djbTrade.setDirect("出");
                djbTrade.setTradeType("消费");
                djbTrade.setBalance(district.getBalance());
                tradeMapper.insertDjbTrade(djbTrade);
            }else{
                district.setVipNoAd(SYS_NO);
            }
            districtMapper.updateDjbDistrict(tmp);
        }
    }

}